package com.ruoyi.yljf.controller.AppController;

import cn.hutool.core.bean.BeanUtil;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.security.annotation.Anonymous;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.yljf.domain.UserQuestionRecord;
import com.ruoyi.yljf.domain.dto.PracticeDTO;
import com.ruoyi.yljf.domain.vo.CourseStatisticsVO;
import com.ruoyi.yljf.domain.vo.QuestionVO;
import com.ruoyi.yljf.mapper.UserQuestionRecordMapper;
import com.ruoyi.yljf.service.IExamSummaryService;
import com.ruoyi.yljf.service.IQuestionService;
import com.ruoyi.yljf.service.IUserQuestionRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * 章节练习 controller
 */
@Anonymous
@RestController
@RequestMapping("api/practiceExam")
public class ApiPracticeExamController extends BaseController {
    @Autowired
    private IQuestionService questionService;

    @Autowired
    private IUserQuestionRecordService userQuestionRecordService;

    @Autowired
    private IExamSummaryService examSummaryService;



    /**
     * 通过传入课程id，返回课程和课程章节 总题目数和用户以完成题目数
     * @param id 课程id
     * @return  课程、章节（名，全部题目数，当前用户以完成题目数）
     */
    @GetMapping("courseStatistics/{id}")
    public AjaxResult getCourseStatistics(@PathVariable("id") Long id) {
        CourseStatisticsVO courseStatistics = questionService.getCourseStatistics(id);
        return AjaxResult.success(courseStatistics);
    }

    /**
     * 通过课程Id和课程章节Id获取试题列表
     * @param courseId：课程Id
     * @param packageId：课程章节Id
     * @return：返回对应试题列表
     */
    @GetMapping("packageQuestionlist")
    public AjaxResult getPackageQuestion(Long courseId, Long packageId) {
        List<QuestionVO> questionVOS = questionService.getQuestionList(courseId, packageId);
        return AjaxResult.success(questionVOS);
    }

    /**
     * 提交章节练习记录
     * @param practiceDTO
     * @return
     */
    @PostMapping("/submitQuestion")
    public AjaxResult submitQuestion(@RequestBody PracticeDTO practiceDTO) {
        UserQuestionRecord userQuestionRecord = BeanUtil.copyProperties(practiceDTO, UserQuestionRecord.class);
        userQuestionRecord.setUserId(SecurityUtils.getUserId());
        userQuestionRecord.setCreateTime(new Date());
        // 更新用户章节练习记录
        userQuestionRecordService.saveUserQuestionRecord(userQuestionRecord);

        // 用户做题记录
        examSummaryService.updateUserPractice(practiceDTO);
        return AjaxResult.success();
    }
}
